package wassalt.client;

import java.util.ArrayList;

import wassalt.Utils.AppConstants;
import wassalt.Utils.DbAdapter;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

public class FavoriteClientsActivity extends ListActivity implements OnClickListener{

	DbAdapter db;
	FavoriteClientsAdapter la;
	public ListView lv;
	public Cursor c;
	Button done;
	Button cancel;
	
	/**
	 * @author Aya Kamel
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.favorites);
		setTitle(getString(R.string.favorites));
		
		//Open the database and fetch all saved favorites
		db = new DbAdapter(this);
		if(!db.isOpened)
			db.open();
		c = db.AllContacts();
		db.close();
		la = new FavoriteClientsAdapter(this, c, AppConstants.FAVORITES);
		setListAdapter(la);
		
		//View the table in a list view
		lv = getListView();
		lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		
		//Set the onClick listener for the list items
		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View v, int pos,
					long id) {
				itemClick(v);
			}
		});

		//Set the onLongClick listener for the list items
		registerForContextMenu(lv);
		lv.setTextFilterEnabled(true);
		lv.setItemsCanFocus(false);
		
		//Configure the text field to filter the contents of the list view according
		//to what is written in the text field
		initializeSearchBar();

		//Set the onClick Listeners for the buttons
		done = (Button) findViewById(R.id.favorites_done);
		done.setOnClickListener(this);
		done.setEnabled(false);
		cancel = (Button) findViewById(R.id.favorites_cancel);
		cancel.setOnClickListener(this);
	}
	
	/**
	 * Whenever a list is clicked, the corresponding check box is checked
	 * @param pos The index of the clicked item
	 * @author Aya Kamel
	 */
	private void itemClick(View v) {
		// TODO Auto-generated method stub
		TextView phn = (TextView)v.findViewById(R.id.contact_phone);
		TextView n = (TextView)v.findViewById(R.id.contact_name);
		String phone_num = (String) phn.getText();
		String name = (String) n.getText();
		la.check(phone_num, name);
		
		int selected_items = la.getNumSelected();
		String text = getString(R.string.done);
		if(selected_items>0)
		{
			done.setEnabled(true);
			text += " ("+selected_items+")";
		}
		else
		{
			done.setEnabled(false);
		}
		done.setText(text);
	}
	
	/**
	 * Initializes the Search bar by setting the onTextChanged listeners
	 * @author Aya Kamel
	 */
	private void initializeSearchBar()
	{
		EditText searching = (EditText) findViewById(R.id.searchField);
		searching.addTextChangedListener(
				new TextWatcher(){
					
			        @Override
			        public void afterTextChanged(Editable arg0){
			            // After text settles fetch all contacts whose names
			        	// contain the string typed in the search box
			        	if(!db.isOpened)
			        		db.open();
			        	Cursor cursor;
			        	if(arg0 != null && !arg0.toString().equals(""))
			        		cursor = db.AllContacts(arg0.toString());
			        	else
			        		cursor = db.AllContacts();
			        	la.changeCursor(cursor);
			        	db.close();
			        }

					@Override
					public void beforeTextChanged(CharSequence arg0, int arg1,
							int arg2, int arg3) {
						// TODO Auto-generated method stub
						
					}

					@Override
					public void onTextChanged(CharSequence arg0, int arg1,
							int arg2, int arg3) {
						// TODO Auto-generated method stub
						
					}
	    });
	}
	
	/**
	 * @author Aya Kamel
	 * @see android.app.Activity#onCreateContextMenu(android.view.ContextMenu, android.view.View, android.view.ContextMenu.ContextMenuInfo)
	 * The long press menu creator
	 */
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenu.ContextMenuInfo menuInfo) {

		super.onCreateContextMenu(menu, v, menuInfo);
		
		//Set menu look-and-feel parameters
		menu.setHeaderTitle("Options");
		menu.setHeaderIcon(R.drawable.settings);
		menu.add(0, AppConstants.MENU_DELETE, 0, getString(R.string.remove_favorite));
	}
	
	/**
	 * @author Aya Kamel
	 * @see android.app.Activity#onMenuItemSelected(int, android.view.MenuItem)
	 * The onClick function for the menu items
	 */
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		
		//Save the request on which the current selection will take place
		final AdapterContextMenuInfo req = (AdapterContextMenuInfo) item.getMenuInfo();
		if(!db.isOpened)
			db.open();
		switch (item.getItemId()) {
			//Create a new notification -- will direct to another list
			case AppConstants.MENU_DELETE:
				TextView v = (TextView)req.targetView.findViewById(R.id.contact_phone);
				String phone = (String) v.getText();
				la.remove(phone);
				db.deleteContact(req.id);
				//c.requery();
				Cursor c1 = db.AllContacts();
				la.changeCursor(c1);
				break;
		}
		db.close();
		return false;
	}

	/**
	 * @author Aya Kamel
	 * @see android.app.Activity#onPause()
	 */
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		Log.i("Activity", "Paused");
		super.onPause();
		db.close();
	}
	
	/**
	 * @author Aya Kamel
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		Log.i("Activity", "Resumed");
		super.onResume();
		if(!db.isOpened)
			db.open();
	}
	
	/**
	 * @author Aya Kamel
	 * @see android.app.Activity#onStop()
	 */
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		Log.i("Activity", "Stopped");
		super.onStop();
	}
	
	/**
	 * Creates a new bundle and inserts the names and phones of chosen contacts
	 * and returns this bundle in an intent with a success message
	 * @author Aya Kamel
	 */
	public void finalize()
	{
		Bundle b = new Bundle();
		Intent intent = new Intent();
		ArrayList<String> names = new ArrayList<String>();
		ArrayList<String> phones = new ArrayList<String>();
		
		for (int i=0; i<la.selected.size(); i++) {
			String name = la.selected.get(i).getName();
			String phone = la.selected.get(i).getPhone();
			names.add(name);
			phones.add(phone);
			Log.i("Favorites", "Position "+i+": ("+name+", "+phone+")");
		}
		
		la.selected.clear();
		b.putStringArrayList("SelectedNames", names);
		b.putStringArrayList("SelectedPhones", phones);
		intent.putExtras(b);
		setResult(AppConstants.SUCCESS, intent);
		finish();
	}
	
	/**
	 * Creates an empty intent with a failure message
	 * @author Aya Kamel
	 */
	public void returnEmpty()
	{
		la.selected.clear();
		Intent intent = new Intent();
		setResult(AppConstants.FAILURE, intent);
		finish();
	}

	/**
	 * Captures the clicks of the buttons and chooses the right
	 * action according to the clicked button
	 * @author Aya Kamel
	 */
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v == done)
			finalize();
		if(v == cancel)
			returnEmpty();
	}
	
}